package com.woniu.aimd.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.woniu.aimd.pojo.DTO.UserDTO;
import com.woniu.aimd.pojo.VO.UserTokenVO;
import com.woniu.aimd.pojo.entity.User;
import com.woniu.aimd.service.UserService;
import com.woniu.aimd.utils.OrderNumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zcnovice
 * @data 2025/6/10 上午11:59
 */

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;


    /**
     * @Description: 测试通过
     * @return:
     * @Author:  zcnovice
     * @date:  2025/6/10 下午1:22
     */
    @PostMapping("/insert")
    public SaResult insert(@RequestBody UserDTO user){
        String id = OrderNumberUtil.generateOrderNumber("user");
        user.setId(id);
        boolean result = userService.insert(user);
        if(!result){
            return SaResult.error("注册失败");
        }
        return SaResult.ok("注册成功");
    }

    /**
     * @Description: 测试通过
     * @return:
     * @Author:  zcnovice
     * @date:  2025/6/10 下午1:22
     */
    @DeleteMapping("/delete")
    public SaResult delete(String userId){
        boolean result = userService.delete(userId);
        if(!result){
            return SaResult.error("删除失败");
        }
        return SaResult.ok("删除成功");
    }

    /**
     * @Description: 测试通过
     * @return:
     * @Author:  zcnovice
     * @date:  2025/6/10 下午1:22
     */
    @PutMapping("/update")
    public SaResult update(@RequestBody User user) {
        boolean result = userService.update(user);
        if(!result){
            return SaResult.error("修改失败");
        }
        return SaResult.ok("修改成功");
    }

    /**
     * @Description:  条件查询 -- 测试通过
     * @return:
     * @Author:  zcnovice
     * @date:  2025/6/10 下午1:29
     */
    @GetMapping("/findByUser")
    public SaResult findByUser(User user){

        List<User> users  = userService.findByUser(user);
        if(users == null){
            return SaResult.error("查询失败");
        }
        return SaResult.data(users);
    }




    @PostMapping("/login")
    public SaResult login(@RequestBody User user,@RequestHeader(value = "Satoken", required = false) String satoken){
            UserTokenVO userVo = userService.login(user,satoken);
            if (userVo.getId() != null ) {
                return SaResult.ok().data(userVo);
            } else {
                return SaResult.error(userVo.getResult());
            }

    }

    //用户登出
    @PostMapping("/logout")
    public SaResult logout(@RequestBody User user){
        StpUtil.logout();
        return SaResult.ok("退出成功");
    }
}
